<!--
 * @Descripttion: 其他类合同管理
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-06-02 17:59:37
 * @LastEditTime: 2022-08-03 17:25:22
 * @FilePath: \cscec-pms-admin\src\views\Legal\branchContract\otherTypesContract\index.vue
-->
<template>
  <!-- 其他类合同管理 -->
  <base-breadcrumb class="flexMemberInfo-container">
    <!-- 搜索 -->
    <searchData
      :search-data="searchOption"
      @search="search"
    />
    <!-- 搜索 -->
    <!-- 其他类合同管理 -->
    <a-card>
      <!-- 表格操作 -->
      <div class="table-operator">
        <!-- <title-name :title="$route.meta.title" /> -->
        <!-- <excel
          ref="exportBtn"
          file-name="其他类合同管理"
          content-title="其他类合同管理"
          is-click-generate="false"
        >
          <a-button
            slot="excelBtn"
            v-btnPermission="'lcm_009_exp_03'"
            type="primary"
            icon="download"
            :loading="exportLoading"
            :disabled="tableLoading || selectExport"
            @click="handleSelectExport"
          >
            导出选中
          </a-button>
          <a-button
            slot="excelBtn"
            v-btnPermission="'lcm_009_exp_03'"
            type="primary"
            icon="download"
            :disabled="tableLoading"
            :loading="exportLoading"
            @click="handleAllExport"
          >
            导出全部
          </a-button>
        </excel> -->
      </div>
      <!-- 表格操作 -->
      <!-- 表格 -->
      <list-table
        ref="table"
        row-key="id"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :export-permission="{ select: 'lcm_009_exp_03', all: 'lcm_009_exp_03' }"
        :export-config="{ use: true, select: '其他类合同管理', all: '其他类合同管理' }"
      >
           <a-button
            slot="prefix"
          v-btnPermission="'lcm_009_add_02'"
          type="primary"
          icon="plus"
          @click="handleAdd"
        >
          新增
        </a-button>
        <template
          slot="reviewAuditStatus"
          slot-scope="text"
        >
          <status-display
            :status-code="text"
            :status-map="dicts.REVIEW_AUDIT_STATUS"
          />
        </template>
        <template
          slot="sealAuditStatus"
          slot-scope="text"
        >
          <status-display
            :status-code="text"
            :status-map="dicts.REVIEW_AUDIT_STATUS"
          />
        </template>
        <span
          slot="operator"
          slot-scope="text,record"
        >
          <MoreButton>
            <a
              v-btnPermission="'lcm_009_loo_01'"
              @click="handleDetail(record)"
            >查看</a>
            <template v-if="(userInfo.currentPost.id === record.businessDepId && (record.reviewAuditStatus ==='DRAFT'||record.reviewAuditStatus ==='REJECTED'))&&hideBuquBtn()">
              <a @click="handleEdit(record)">编辑</a>
            </template>
            <template v-if="record.reviewAuditStatus==='DRAFT'&&hideBuquBtn()">
              <a @click="handleDelete(record)">删除</a>
            </template>
            <template v-if="(userInfo.currentPost.id === record.businessDepId && record.reviewAuditStatus!=='DRAFT' && record.sealAuditStatus!=='SUBMITTED' && record.sealAuditStatus!=='PAST')&&hideBuquBtn()">
              <a @click="handleUseSeal(record,record.sealAuditStatus)">用印</a>
            </template>
            <template v-if="record.reviewAuditStatus!=='DRAFT'">
              <a @click="handleApproval(record)">审批详情</a>
            </template>
          </MoreButton>
        </span>
      </list-table>
    </a-card>
    <!-- 其他类合同管理 -->
    <!-- 审批详情 -->
    <ApprovalDetails
      :business-id="approvalDetailsDialog.businessId"
      :seal-business-id="approvalDetailsDialog.sealBusinessId"
      :visible.sync="approvalDetailsDialog.visible"
    />
    <!-- 审批详情 -->
  </base-breadcrumb>
  <!-- 其他类合同管理 -->
</template>
<script>
import { STable } from '@/components'
import StatusDisplay from '@/components/StatusDisplay'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import OrgTreeSelect from '@/components/OrgTreeSelect'
import otherTypesContract from '@/api/legal/branchContract/otherTypesContract'
import ApprovalDetails from './components/ApprovalDetails'
export default {
  name: 'OtherTypesContract',
  components: {
    STable,
    StatusDisplay,
    ApprovalDetails
  },
  data() {
    return {
      // 接口响应代码
      resCode: 200,
      // 登录人信息
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      // 搜索选项
      searchOption: [
        {
          name: '所属单位',
          valueKey: 'searchQuery',
          type: OrgTreeSelect,
        },
        // {
        //   name: '业务主办单位',
        //   valueKey: 'businessDepId',
        //   type: SelectCompanyAndProject
        // },
        {
          name: '合同名称',
          value: 'contractName',
          type: 'input'
        },
        {
          name: '合同对方名称',
          value: 'otherParty',
          type: 'input'
        },
        {
          name: '合同价(万元)',
          value: 'amount',
          type: 'rangeInput'
        },
        {
          name: '创建人',
          value: 'creatorName',
          type: 'input'
        },
        {
          name: '创建时间',
          value: 'createTime',
          type: 'dateRange'
        }
      ],
      // 表格选中项
      selectedRowKeys: [],
      // 表格复选
      rowSelection: {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys) => {
          this.selectedRowKeys = selectedRowKeys
        }
      },
      // 表头
      columns: [
        {
          title: '序号',
          width: '80px',
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '业务主办单位',
          dataIndex: 'businessDepName',
          key: 'businessDepName',
          align: 'center'
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          key: 'contractName'
        },
        {
          title: '合同价(万元)',
          dataIndex: 'amount',
          key: 'amount'
        },
        {
          title: '合同对方',
          dataIndex: 'otherParty',
          key: 'otherParty'
        },
        {
          title: '创建人',
          dataIndex: 'creatorName',
          key: 'creatorName'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '状态',
          dataIndex: 'reviewAuditStatus',
          key: 'reviewAuditStatus',
          width: '140px',
          scopedSlots: { customRender: 'reviewAuditStatus' }
        },
        {
          title: '用印状态',
          dataIndex: 'sealAuditStatus',
          key: 'sealAuditStatus',
          width: '140px',
          scopedSlots: { customRender: 'sealAuditStatus' }
        },
        {
          title: '操作',
          dataIndex: 'operator',
          width: '240px',
          scopedSlots: { customRender: 'operator' }
        }
      ],
      // 字典
      dicts: {
        REVIEW_AUDIT_STATUS: {
          DRAFT: {
            label: '待提交',
            color: '#FFDF25'
          },
          SUBMITTED: {
            label: '审核中',
            color: '#108EE9'
          },
          PAST: {
            label: '审核通过',
            color: '#2EBA07'
          },
          REJECTED: {
            label: '审核不通过',
            color: '#FB0000'
          }
        }
      },
      // 搜索数据
      searchData: {},
      // 表格加载
      tableLoading: true,
      // 导出加载
      exportLoading: false,
      // 导出选中禁用
      selectExport: true,
      // 表格数据
      table: [],
      // 表格总数
      total: 0,
      //审批详情
      approvalDetailsDialog: {
        visible: false,
        businessId: '',
        sealBusinessId: ''
      },
      loadData: (parameter) => {
        const params = Object.assign({}, parameter, this.searchData)
        if (this.searchData?.createTime?.length > 0) {
          params.createTimeStart = this.searchData.createTime[0].format('YYYY-MM-DD') || void 0
          params.createTimeEnd = this.searchData.createTime[1].format('YYYY-MM-DD') || void 0
        }
        return otherTypesContract.findListByMain(params).then((res)=>{
          return res;
        })
      },
    }
  },
  watch: {
    selectedRowKeys: {
      handler(newV) {
        this.selectExport = !(newV.length > 0)
      }
    }
  },
  methods: {
    /**
     * @description: 搜索
     * @param {Object} value 搜索数据
     * @return {Void}
     */
    search(value) {
      this.searchData = value || {}
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 表格数据加载方法
     * @param {Object} parameter 分页信息
     * @return {Promise} 接口Promise
     */
    // async loadData(parameter) {
    //   try {
    //     const params = Object.assign({}, parameter, this.searchData)
    //     if (this.searchData?.createTime?.length > 0) {
    //       params.createTimeStart = this.searchData.createTime[0].format('YYYY-MM-DD') || void 0
    //       params.createTimeEnd = this.searchData.createTime[1].format('YYYY-MM-DD') || void 0
    //     }
    //     this.tableLoading = true
    //     const { data, currentPage, totalSize } = await otherTypesContract.findListByMain(params)
    //     console.log(data,'data')
    //     this.table = data
    //     this.total = totalSize
    //     this.tableLoading = false
    //     return Promise.resolve({
    //       data: data,
    //       currentPage: currentPage,
    //       totalSize: totalSize
    //     })
    //   } catch (error) {
    //     console.log(error)
    //     return Promise.reject(error)
    //   }
    // },
    /**
     * @description: 新增
     * @param {Void}
     * @return {Void}
     */
    handleAdd() {
      this.$router.push({
        path: '/legal/branch-contract/otherTypesContract/add',
        query: {
          pageType: 'add'
        }
      })
    },
    /**
     * @description: 处理表格导出数据
     * @param {Array} data 表格数据
     * @return {Object} {list:表格数据，columns：表头}
     */
    handleTableDataToExport(data) {
      const list = (data || []).map((el, index) => {
        const item = JSON.parse(JSON.stringify(el))
        item.index = index + 1
        item.reviewAuditStatus = this.dicts.REVIEW_AUDIT_STATUS[item.reviewAuditStatus]?.label
        item.sealAuditStatus = this.dicts.REVIEW_AUDIT_STATUS[item.sealAuditStatus]?.label
        return item
      })
      const columns = [
        {
          title: '序号',
          dataIndex: 'index'
        },
        {
          title: '业务主办单位',
          dataIndex: 'businessDepName'
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          key: 'contractName'
        },
        {
          title: '合同价(万元)',
          dataIndex: 'amount',
          key: 'amount'
        },
        {
          title: '合同对方',
          dataIndex: 'otherParty',
          key: 'otherParty'
        },
        {
          title: '创建人',
          dataIndex: 'creatorName',
          key: 'creatorName'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '状态',
          dataIndex: 'reviewAuditStatus'
        },
        {
          title: '用印状态',
          dataIndex: 'sealAuditStatus'
        }
      ]
      return {
        list,
        columns
      }
    },
    /**
     * @description: 导出全部
     * @param {Void}
     * @return {Void}
     */
    async handleAllExport() {
      if (!this.total) {
        this.$message.warning('没有可导出数据')
        return
      }
      this.exportLoading = true
      try {
        const params = Object.assign(
          {},
          {
            pageNo: 1,
            pageSize: this.total
          },
          this.searchData
        )
        if (this.searchData?.createTime?.length > 0) {
          params.createTimeStart = this.searchData.createTime[0].format('YYYY-MM-DD') || void 0
          params.createTimeEnd = this.searchData.createTime[1].format('YYYY-MM-DD') || void 0
        }
        const { data } = await otherTypesContract.findListByMain(params)
        const { list, columns } = this.handleTableDataToExport(data)
        this.$refs.exportBtn.generateExcel(list, { columns }, 0)
      } catch (error) {
        console.log(error)
      } finally {
        this.exportLoading = false
      }
    },
    /**
     * @description: 导出选中
     * @param {Void}
     * @return {Void}
     */
    handleSelectExport() {
      this.exportLoading = true
      try {
        const data = this.table.filter((el) => this.selectedRowKeys.includes(el.id))
        const { list, columns } = this.handleTableDataToExport(data)
        this.$refs.exportBtn.generateExcel(list, { columns }, 0)
      } catch (error) {
        console.log(error)
      } finally {
        this.exportLoading = false
      }
    },
    /**
     * @description: 查看
     * @param {Object} record 行数据
     * @return {Void}
     */
    handleDetail(record) {
      this.$router.push({
        path: '/legal/branch-contract/otherTypesContract/detail',
        query: {
          id: record.id
        }
      })
    },
    /**
     * @description: 编辑
     * @param {Object} record 行数据
     * @return {Void}
     */
    handleEdit(record) {
      this.$router.push({
        path: '/legal/branch-contract/otherTypesContract/add',
        query: {
          pageType: 'edit',
          id: record.id
        }
      })
    },
    /**
     * @description: 删除
     * @param {Object} record 行数据
     * @return {Void}
     */
    handleDelete(record) {
      this.$confirm({
        title: '温馨提示',
        content: '确定是否删除数据？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          otherTypesContract.deleteBymain({ ids: [record.id] }).then(({ code }) => {
            if (code === this.resCode) {
              this.$message.success('删除成功')
              this.$refs.table.refresh(true)
            } else {
              this.$message.warning('删除失败')
            }
          })
        }
      })
    },
    /**
     * @description: 用印
     * @param {Object} record 行数据
     * @param {String} sealAuditStatus 用印状态
     * @return {Void}
     */
    handleUseSeal(record, sealAuditStatus) {
      this.$router.push({
        path: 'legal/branch-contract/otherTypesContract/seal',
        query: {
          pageType: sealAuditStatus === null ? 'add' : 'edit',
          id: record.id
        }
      })
    },
    /**
     * @description: 审批详情
     * @param {Object} record 行数据
     * @return {Void}
     */
    handleApproval(record) {
      this.approvalDetailsDialog.visible = true
      this.approvalDetailsDialog.businessId = record.id
      this.approvalDetailsDialog.sealBusinessId = record.sealBusinessId
      console.log(this.approvalDetailsDialog)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
